package com.xinnet.mms.customtransfer.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerstate.dao.CustomerStateHistDao;
import com.xinnet.mms.customtransfer.service.OfServiceCustomTransferService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.enums.ProductTypeEnum;
import com.xinnet.mms.order.dao.OrderDao;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.product.dao.ProductDao;
import com.xinnet.mms.utils.CustomerManage;

@Service("ofServiceCustomTransferService")
public class OfServiceCustomTransferServiceImpl implements OfServiceCustomTransferService{
	
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private CustomerStateHistDao customerStateHistDao;
	@Autowired
	private OrderDao orderDao;
	/**xinne库--订单*/
	@Autowired
	private  OrderService orderService;
	@Autowired
	private EmpCustomRelationDao empCustomRelationDao;
	
	private static Logger log=LoggerFactory.getLogger(OfServiceCustomTransferServiceImpl.class);
	/**
	 * 服务期客户流转
	 */
	public void ofServiceCustomTransfer() throws Exception{
		//获取产品规则
		Map<String,Product> productRuleMap = AppGlobalContainer.productRuleMap;
		if(productRuleMap==null || productRuleMap.isEmpty()){
			return;
		}
		/*Map<Integer,List<EmpCustomRelation>> customerMap = (Map<Integer,List<EmpCustomRelation>>)AppGlobalContainer.transferCustomMap;
		if(customerMap==null || customerMap.isEmpty()){
			return;
		}
		//获取服务期客户
		List<EmpCustomRelation> ofServiceCustomList = customerMap.get(CustomerManage.SERVICE_CUSTOMER);
		if(ofServiceCustomList==null || ofServiceCustomList.isEmpty()){
			log.info("服务期客户为空");
			return;
		}*/
        String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }
        
        
		//服务期客户流转
        log.info("************************************************************************************服务期客户流转开始********************************************");
        //回收客户流转
        //分页获取新注册客户信息
        Customer customer = new Customer();
        customer.setCustomType(CustomerManage.SERVICE_CUSTOMER);
        int count = empCustomRelationDao.getTransferCustomCount(customer);
        
        PageView<Customer> page = new PageView<Customer>();
        page.setPageSize(50000); //每页显示5w条
        page.setRowCount(count);
        long pageCount = page.getPageCount();
        
        for(int i = 1;i<=pageCount;i++){
        	page.setPageNow(i);
        	Integer startPage = page.getFirstResult();
    		customer.setLimitTop(startPage);
    		customer.setLimitDown(page.getPageSize());
        	
        	List<EmpCustomRelation> retrieveCustomList = empCustomRelationDao.getTransferCustom(customer);
        	for(int j=0;j<retrieveCustomList.size();j++){
    			EmpCustomRelation ofServiceCustom = retrieveCustomList.get(j);
    			this.customTransferForOfServiceCustomer(ofServiceCustom, isTest);
    		}
        }
		log.info("************************************************************************************服务期客户流转完毕********************************************");
	}

	/**
	 * 对每个服务期客户流转
	 * @param newRegisterCustom
	 * @param isTest
	 * @param transferRuleList
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void customTransferForOfServiceCustomer(EmpCustomRelation ofServiceCustom,String isTest){
		
		
		try {
			Customer customer = customAllotService.getCustomerById(ofServiceCustom.getCustomId());
			List<CustomerCare> orderList=orderService.getOrdersByCusId(ofServiceCustom.getCustomId());
			if (orderList == null || orderList.isEmpty()) {
				log.info("会员号:【"+customer.getCusId()+"】没有购买过商品");
				return;
			}
			//去重复的商品
			/*List<String> tempProductIiList= new ArrayList<String>();
			List<CustomerCare> tempOrderList = new ArrayList<CustomerCare>();
			
			for(CustomerCare care:orderList) {
				if(care==null || care.getProductId()==null) {
					continue;
				}
				
				if(!tempProductIiList.contains(care.getProductId())){
					tempProductIiList.add(care.getProductId());
					tempOrderList.add(care);
				}
			}*/
			
			List<Customer> customerList = new ArrayList<Customer>();
			for(CustomerCare care:orderList) {
		 		
				if(care.getProductId().substring(0,1).equals("V")) {
					customer.setProductLabel("V");
					List<Customer> cList = orderDao.queryVhostService(customer);
					if(cList==null || cList.size()==0) {
						//log.info("会员号:"+customer.getCusId()+"产品未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
					
				}
				//如果拿到的产品code是CHFW(云主机) 则强制设置为NYZJ(本系统内能识别的云主机CODE)
				else if(care.getProductId().equals(CustomerManage.CHFW)||care.getProductId().equals("NYZJ") ||care.getProductId().equals("XNYY")) {
					if(care.getProductId().equals(CustomerManage.CHFW)){
						customer.setProductLabel("NYZJ");
					} else {
						customer.setProductLabel(care.getProductId());
					}
					
					List<Customer> cList = orderDao.queryIdcServerService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
					if(care.getProductId().equals(CustomerManage.CHFW)){
						customer.setProductLabel("NYZJ");
					} else {
						customer.setProductLabel(care.getProductId());
					}
				}
				//如果拿到的产品code是ZJTG(主机托管) 则强制设置为ZJZY(主机租用)
				else if(care.getProductId().equals(CustomerManage.ZJTG)||care.getProductId().equals("ZJZY")) {
					customer.setProductLabel(CustomerManage.ZJTG);
					List<Customer> cList = orderDao.queryIdcService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
					customer.setProductLabel(ProductTypeEnum.Hosting.getValue());
				}
				else if(care.getProductId().equals(CustomerManage.MEJZ)) {
					customer.setProductLabel(CustomerManage.MEJZ);
					List<Customer> cList = orderDao.queryJianzhanService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);
					}
					customer.setProductLabel(ProductTypeEnum.Jianzhan.getValue());
				}
				else if(care.getProductId().indexOf("EC")!=-1){
					customer.setProductLabel(care.getProductId());
					List<Customer> cList = orderDao.queryChiYunService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
					customer.setProductLabel(ProductTypeEnum.ChiYun.getValue());
				}
				else if(care.getProductId().substring(0, 1).equals(CustomerManage.D)){
					customer.setProductLabel(CustomerManage.D);
					List<Customer> cList = orderDao.queryDomainService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						return;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
				}
				else if(care.getProductId().substring(0, 1).equals("M")){
					customer.setProductLabel("M");
					List<Customer> cList = orderDao.queryMailboxService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						continue;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
				}
				
				else if(care.getProductId().equals(ProductTypeEnum.A_365.getValue())){
					customer.setProductLabel(ProductTypeEnum.A_365.getValue());
					List<Customer> cList = orderDao.queryOffice365Service(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						continue;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
				}
				
				else if(care.getProductId().equals(ProductTypeEnum.A_NOFC.getValue())){
					customer.setProductLabel(ProductTypeEnum.A_NOFC.getValue());
					List<Customer> cList = orderDao.queryNewOfficeService(customer);
					if(cList==null ||cList.size()==0) {
						//log.info("会员号:【"+customer.getCusId()+"】产品【"+customer.getProductLabel()+"】未开通");
						continue;
					}
					if(cList.get(0)!=null){
						Customer c = cList.get(0);
						customerList.add(c);;
					}
				}
			}
			SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(customerList.size()==0){
				return;
			}
			java.util.Collections.sort(customerList,new Comparator<Customer>(){

				@Override
				public int compare(Customer c1, Customer c2) {
					
					return c2.getDueTime().compareTo(c1.getDueTime());
				}
			});
			
			String customId = customer.getCusId();
			List<Product> productList =productDao.getALLProduct();
			String productId =null;
			for (Product product : productList) {
				if(product.getProductCode().equals(customer.getProductLabel())){
					productId = product.getId();
				}
			}
			
			if(productId==null || "".equals(productId)){
				log.info("当前产品ID: is null  return");
				return;
			}
			Customer customerEndTime = customerList.get(0);
			
			String regionalId = ofServiceCustom.getRegionalId();
			String companyId = customer.getCompanyId();
			customer.setCompanyId(ofServiceCustom.getCompanyId());
			String empNo = ofServiceCustom.getEmpId();
			String pushHistId = ofServiceCustom.getPushHistId();
			
			if(customerEndTime.getBuyTime()==null||customerEndTime.getDueTime()==null){
				log.info("会员号:【"+customer.getCusId()+"】产品【"+customerEndTime.getProductLabel()+"】服务时间为空");
				return;
			}
			
			if("".equals(customerEndTime.getBuyTime())||"".equals(customerEndTime.getDueTime())){
				log.info("会员号:【"+customer.getCusId()+"】产品【"+customerEndTime.getProductLabel()+"】服务时间为空");
				return;
			}
			
			if("0000-00-00 00:00:00".equals(customerEndTime.getBuyTime())||"0000-00-00 00:00:00".equals(customerEndTime.getDueTime())){
				log.info("会员号:【"+customer.getCusId()+"】产品【"+customerEndTime.getProductLabel()+"】服务时间为空");
				return;
			}
			
			Date buyDate = sdf.parse(customerEndTime.getBuyTime());
			Date dueDate = sdf.parse(customerEndTime.getDueTime());
			
			
			/*Map<String,CustomerCare> customerCareMap = AppGlobalContainer.customerCareMap;
			CustomerCare customerCare = customerCareMap.get(customId+"_"+productCode);
			if(customerCare!=null){
				Date tempBuyDate = customerCare.getBuyDate();
				Date tempDueDate = customerCare.getDueTime();
				if(tempBuyDate==null || tempDueDate==null){
					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String transferTime = sdf.format(new Date());
					log.info("订单数据异常【customerCareMap != null】：购买日期为空或结束日期为空。删除客户ID为："+customId+",产品code: "+ productCode + "  "+transferTime);
					return;
				}
				buyDate=tempBuyDate;
				dueDate=tempDueDate;
				
			}else{
				Map<String,CustomerCare> delCustomerCareMap = AppGlobalContainer.delCustomerCareMap;
				CustomerCare tempCustomerCare = delCustomerCareMap.get(customId+"_"+productCode);
				if(tempCustomerCare==null){
					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String transferTime = sdf.format(new Date());
					log.info("订单数据异常【delCustomerCareMap.get(customId_productCode) = null】：购买日期为空或结束日期为空。删除客户ID为："+customId+",产品code: "+ productCode + "  " + transferTime);
					return;
				}
				Date tempBuyDate = tempCustomerCare.getBuyDate();
				Date tempDueDate = tempCustomerCare.getDueTime();
				if(tempBuyDate==null || tempDueDate==null){
					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String transferTime = sdf.format(new Date());
					log.info("订单数据异常【delCustomerCareMap.get(customId_productCode) != null】：购买日期为空或结束日期为空。删除客户ID为："+customId+",产品code: "+ productCode + "  "+transferTime);
					return;
				}
				buyDate=tempCustomerCare.getBuyDate();
				dueDate=tempCustomerCare.getDueTime();	
			}
			
			if(buyDate==null || buyDate==null){
				SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String transferTime = sdf.format(new Date());
				log.info("订单数据异常：购买日期为空或结束日期为空。删除客户ID为："+customId+"  "+transferTime);
				return;
			}*/
			Product currentProductRule=AppGlobalContainer.productRuleMap.get(productId);
			if(currentProductRule==null){
				log.info("当前产品规则productId: "+productId+"不可用  return");
				return;
			}

			Date currentDate = new Date();
			//客户没有到期   不做处理
			if(currentDate.before(dueDate)){
				/*//进入服务期前几天不可见
				Integer startServiceCycle = currentProductRule.getStartServiceCycle();
				//服务期末几天不可见
				Integer endServiceCycle = currentProductRule.getEndServiceCycle();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(buyDate);
				if("true".equals(isTest)){
					calendar.add(Calendar.MINUTE, startServiceCycle);
				}else if("false".equals(isTest)){
					calendar.add(Calendar.DATE, startServiceCycle);
				}else{
					log.info("环境异常  是否测试  return");
					return;
				}
				//服务期可见时间
				Date ofServiceDisplay=calendar.getTime();
				calendar.setTime(dueDate);
				if("true".equals(isTest)){
					calendar.add(Calendar.MINUTE, -endServiceCycle);
				}else if("false".equals(isTest)){
					calendar.add(Calendar.DATE, -endServiceCycle);	
				}else{
					log.info("环境异常  是否测试  return");
					return;
				}
				//服务期末不可见时间
				Date ofServiceEndNoDisplay=calendar.getTime();
				calendar.setTime(dueDate);
				if(currentDate.after(ofServiceDisplay) &&  currentDate.before(ofServiceEndNoDisplay)){
					//剔除在二次开发中的服务期客户
					List<CustomStateHist> cshList=customerStateHistDao.getReceiveCustomStateHistByCustomId(customId);
					List<Integer> typeList=new ArrayList<Integer>();
					
					for(CustomStateHist csh:cshList) {
						if(!typeList.contains(csh.getCustomType())) {
							typeList.add(csh.getCustomType());
						}
					}
					if(typeList.contains(CustomerManage.TWICE_CUSTOMER)) {
						return;
					}
					//服务期可见，流转为二次开发客户
					log.info("服务期客户流转成二次开发客户开始：customer id"+customId+",产品code: "+ productCode + "  "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					Map<String,List<CustomStateHist>> customStateHistMap = AppGlobalContainer.customStateHistMap;
					List<CustomStateHist> customStateHistList = customStateHistMap.get(customId);
					Product pushProduct = AppGlobalContainer.getPushProduct(currentProductRule,customStateHistList);
					if(pushProduct!=null){
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
						
						Customer ofServiceCustomer = new Customer();
						String pushProductName = pushProduct.getProductName();
						String pushProductId = pushProduct.getId();
						String pushProductCode = pushProduct.getProductCode();
						ofServiceCustomer.setProductLabel(pushProductCode);
						ofServiceCustomer.setProductId(pushProductId);
						ofServiceCustomer.setProductName(pushProductName);
						ofServiceCustomer.setRegionalId(regionalId);
						ofServiceCustomer.setCompanyId(companyId);
						ofServiceCustomer.setCusId(customId);
						ofServiceCustomer.setPushHistId(pushHistId);
						ofServiceCustomer.setCustomerType(CustomerManage.TWICE_CUSTOMER);
						//系统推送
						customAllotService.allot(ofServiceCustomer,CustomerManage.TWICE_CUSTOMER);
						log.info("服务期客户流转成二次开发客户结束：customer id"+customId+",产品code: "+ productCode +"  " +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					}		
				}*/
			}else{
				if(customer.getCustomerType().equals(CustomerManage.OPEN_SEA_CUSTOMER)) {
					log.info("<已经进入公海无需重复推送【"+customer.getCusId()+"】>");
					return;
				}
				log.info("服务期客户进入公海开始：customer id"+customId+",产品code:"+ productId +" "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				//客户已到期,判断是否进入公海时间	(是否有其它产品在服务期，没有进公海)
				Integer endServiceGoOpenSea = currentProductRule.getGoOpenseaTime();//服务期后进公海
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(dueDate);
				calendar.add(Calendar.DAY_OF_YEAR,endServiceGoOpenSea);
				Date goOpenSeaDate = calendar.getTime();//服务期后进公海时间
				if(currentDate.after(goOpenSeaDate)){
					/*List<Product>  productList = productDao.queryEnableProduct();
					 if(productList!=null){
						 boolean isCanGoOpenSea =true;
						 for (Iterator<Product> iterator2 = productList.iterator(); iterator2.hasNext();) {
							Product product = (Product) iterator2.next();
							String id = product.getId();
							Integer tempEndServiceGoOpenSea = product.getGoOpenseaTime();//服务期后进公海
							String tempProductCode1 = product.getProductCode();
							if(!id.equals(productId)){
								List<CustomerCare> tempCustomerCareList =orderDao.getOrdersByCusIdAndProductCode(customId, tempProductCode1);
								if(tempCustomerCareList!=null &&tempCustomerCareList.size()>0 && tempCustomerCareList.get(0)!=null){
									for (Iterator<CustomerCare> iterator3 = tempCustomerCareList.iterator(); iterator3.hasNext();) {
										CustomerCare customerCare2 = (CustomerCare) iterator3.next();
										Date tempDueTime = customerCare2.getDueTime();
										Calendar tempCalendar = Calendar.getInstance();
										tempCalendar.setTime(tempDueTime);
										tempCalendar.add(Calendar.DATE,tempEndServiceGoOpenSea);
										Date tempGoOpenSeaDate = calendar.getTime();
										if(currentDate.before(tempGoOpenSeaDate)){
											isCanGoOpenSea=false;
											break;
										}
									}
								}
							}
						}*/
						//if(isCanGoOpenSea){
						if(customer.getCustomerType().equals(CustomerManage.OPEN_SEA_CUSTOMER)) {
							log.info("<已经进入公海无需重复推送【"+customer.getCusId()+"】>");
							return;
						}
						customerStateHistDao.updateCustomStateHistByCustomIdAndEmpNo(customId,empNo,productId);
						//进入公海
						//Customer customer = new Customer();
						customer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
						customer.setCusId(customId);
						customer.setIsBuy(CustomerManage.BUY_YES);
						customer.setProductId(productId);
						customer.setDeptId(ofServiceCustom.getDeptno());
						customerManageDao.goOpenSea(customer);
						customer.setPushHistId(pushHistId);
						customAllotService.allot(customer, CustomerManage.OPEN_SEA_CUSTOMER);
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
						log.info("服务期客户进入公海：customer id"+customId+",产品code:" +productId+ " " +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
						//}	 
					 /*}else{
						 if(tempCustomer.getCustomerType().equals(CustomerManage.OPEN_SEA_CUSTOMER)) {
								log.info("<已经进入公海无需重复推送>");
								return;
						 }
						 empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
						 customerStateHistDao.updateCustomStateHistByCustomIdAndEmpNo(customId,empNo,productId);
						//进入公海
						Customer customer = new Customer();
						customer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
						customer.setCusId(customId);
						customer.setIsBuy(CustomerManage.BUY_YES);
						customerManageDao.goOpenSea(customer);
						customer.setPushHistId(pushHistId);
						customAllotService.allot(customer, CustomerManage.OPEN_SEA_CUSTOMER);
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
						log.info("服务期客户进入公海：customer id"+customId+",产品code: "+ productCode +"  " +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					 }*/
				}
			}
		} catch (Exception e) {
			log.error("服务期客户流转异常：customer id"+ofServiceCustom.getCustomId()+",产品code: "+ ofServiceCustom.getProductCode() +"  " +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),e);
		}
	}

}
